package com.pearadmin.pro.common.utils.upload.controller;

import com.pearadmin.pro.common.aop.annotation.Log;
import com.pearadmin.pro.common.constant.ControllerConstant;
import com.pearadmin.pro.common.tools.core.StringUtil;
import com.pearadmin.pro.common.utils.IPUtils;
import com.pearadmin.pro.common.utils.upload.DownLoadUtils;
import com.pearadmin.pro.common.utils.upload.FileUploadUtils;
import com.pearadmin.pro.common.web.base.BaseController;
import com.pearadmin.pro.common.web.domain.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

@Log4j2
@Api(tags = {"上传工具"})
@RestController
@RequestMapping(ControllerConstant.PREFIX_SYS + "upload")
public class UploadController extends BaseController {
    @Autowired
    private DownLoadUtils downLoadUtils;


    @PostMapping("/uploadFiles")
    @Log(title = "上传文件")
    @ApiOperation(value = "上传文件")
    public Result uploadAvatar(@RequestParam("file") MultipartFile file, HttpServletRequest request) {
        Map<String, String> map = new HashMap<>();
        String url = "http://" + IPUtils.getIpAddr(request) + ":9292/" + ControllerConstant.PREFIX_RESOURCE_FILE;
//        String url = "http://" + "59.110.234.223" + ":9292/" +"resource/mnt/apps/xiaojizonghepingtai";
        if (!file.isEmpty()) {
            try {
                long size = file.getSize();
                //单位换算
                String s = unitConversion(size);
                url += FileUploadUtils.upload(file, request);
                map.put("url", url);
                map.put("size", s);
                return success(map);
            } catch (IOException e) {
                e.printStackTrace();
                return failure(e.getMessage());
            }
        } else {
            return failure("文件上传发生异常");
        }
    }

    @PostMapping("/uploadFiles1")
    @ApiOperation(value = "上传文件")
    public Object uploadFile(@RequestParam("file") MultipartFile file, HttpServletRequest request) {
        Map<String, Object> map = new HashMap<>();
        Map<String, Object> dataMap = new HashMap<>();
        String url = "http://" + IPUtils.getIpAddr(request) + ":9292/" + ControllerConstant.PREFIX_RESOURCE_FILE;
//        String url = "http://" + "59.110.234.223" + ":9292/" +"resource/mnt/apps/xiaojizonghepingtai";
        if (!file.isEmpty()) {
            try {
                long size = file.getSize();
                //单位换算
                String s = unitConversion(size);
                url += FileUploadUtils.upload(file, request);
                map.put("errno",0);
                dataMap.put("url",url);
                map.put("data",dataMap);
                return map;
            } catch (IOException e) {
                e.printStackTrace();
                map = new HashMap<>();
                map.put("errno",1);
                map.put("message",e.getMessage());
                return map;
            }
        } else {
            return failure("文件上传发生异常");
        }
    }


    @PostMapping("/deleteFiles")
    @Log(title = "删除文件")
    @ApiOperation(value = "删除文件")
    public Result uploadAvatar(@RequestBody String param, HttpServletRequest request) {

        String url = "http://" + IPUtils.getIpAddr(request) + ":9292/" + ControllerConstant.PREFIX_RESOURCE_FILE;
//        String url = "http://" + "59.110.234.223" + ":9292/" +"resource/mnt/apps/xiaojizonghepingtai";
        if(StringUtil.isEmpty(param)){
            return failure("参数为空");
        }
        String str2=param.substring(url.length()+10);
        log.info(FileUploadUtils.defaultBaseDir+str2);
        File file = new File(FileUploadUtils.defaultBaseDir+str2);
        FileUploadUtils.replaceFile(file);
        return success(param);
    }



    @GetMapping("/downloadDocument")
//    @Log(title = "下载文件")
    @ApiOperation(value = "下载文件")
    public Result downloadDocument(HttpServletRequest request, HttpServletResponse response) {
        String param = request.getParameter("folderPath");
        // 这一步是为了去除路径最后面得哪个  “
        String[] pathSplit = param.split("\"");
        String folderPath = pathSplit[0];

//        String url = "http://" + "59.110.234.223" + ":9292/" +"resource/mnt/apps/xiaojizonghepingtai";
        String url = "http://" + IPUtils.getIpAddr(request) + ":9292/" + ControllerConstant.PREFIX_RESOURCE_FILE;
        String defaultBaseDir = FileUploadUtils.defaultBaseDir;
        String str2=folderPath.substring(url.length()+10);
        System.out.println(defaultBaseDir+str2);
//        String[] aa = folderPath.split("/",6);
        // 实际路径+文件名称
        String path = defaultBaseDir + str2;

        File file = new File(path);
        byte[] bytes = new byte[0];
        try {
            bytes = downLoadUtils.fileToByteArray(file);
        } catch (IOException e) {
            e.printStackTrace();
            return failure(String.valueOf(e));
        }
        String[] split = folderPath.split("/"); // split[1]上传类型
        String s = split[8];
        System.out.println(s);
        downLoadUtils.downloadFile(s, bytes, response);
        return success();
    }

    public static void main(String[] args) {
        String fo = "D:\\resource\\2022\\04\\24\\ca78e537-147c-4cc2-80fa-941da36637d5.txt\"";
        String[] split = fo.split("\"");
        System.out.println(split[0]);
    }

    /**
     * 单位转换
     *
     * @param size 字节大小
     * @return java.lang.String
     * @author ZhouXingYun
     * @date 2022/4/20 14:44
     */
    public String unitConversion(long size) {
        BigDecimal bigDecimal = new BigDecimal(size);
        // 不足两位小数补0
        DecimalFormat decimalFormat = new DecimalFormat("0.0#");
        if (size >= 0 && size < 1024) {
            //使用字节单位
            return size + "Bytes";
        } else if (size >= 1024 && size < 1048576) {
            // 使用千字节单位
            BigDecimal divide = bigDecimal.divide(new BigDecimal(1024));
            return decimalFormat.format(divide) + "KB";
        } else if (size >= 1048576 && size < 1073741824) {
            // 使用兆字节单位
            BigDecimal divide = bigDecimal.divide(new BigDecimal(1048576));
            return decimalFormat.format(divide) + "MB";
        } else if (size >= 1073741824) {
            // 使用千兆字节单位
            BigDecimal divide = bigDecimal.divide(new BigDecimal(1073741824));
            return decimalFormat.format(divide) + "GB";
        } else {
            return "未知大小";
        }
    }

}
